package com.sry.blog.utils;

import cn.hutool.core.lang.UUID;
import com.sry.blog.enums.CheckToken;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;

public class TokenUtil {

    //设置过期时间
    private static final long EXPIRE_DATE = 24 * 60 * 60 * 1000;
    //token秘钥
    private static final String TOKEN_SECRET = "token";

    public static String token(String username, String password) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userName", username);
        map.put("passWord", password);
        return Jwts.builder()
                .setSubject(map.toString())
                .setIssuedAt(new Date())
                .setId(UUID.fastUUID().toString(true))
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_DATE))
                .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET)
                .compact();
    }

    public static CheckToken verifyToken(String token) {
        try {
            //验证Token
            JwtParser parser = Jwts.parser();
            parser.setSigningKey(TOKEN_SECRET);
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            String subject = body.getSubject();
            String userName = body.get("userName", String.class);
            String passWord = body.get("passWord", String.class);
//            System.out.println(userName);
//            System.out.println(passWord);
            return CheckToken.SUCCESS;
        } catch (ExpiredJwtException e) {
            return CheckToken.EXPIRED;
        } catch (UnsupportedJwtException e) {
            return CheckToken.ILLEGAL;
        } catch (Exception e) {
            return CheckToken.ELSE;
        }

    }

    public static void main(String[] args) {
        final String token = TokenUtil.token("sry", "admin");
        System.out.println(token);
        System.out.println(TokenUtil.verifyToken(token));
    }
}